﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TestClient_console.Core
{
    public static class StaticHelpers
    {
        public static FileStream fs = null;

        public static void Log(string msg)
        {
            msg = DateTime.Now.ToLongTimeString() + " >>> " + msg + "\n";
            Console.Write(msg);

            if (fs == null)
            {
                InitLogger();
            }

            fs.Write(Encoding.UTF8.GetBytes(msg + Environment.NewLine), 0, Encoding.UTF8.GetByteCount(msg + Environment.NewLine));
            fs.Flush();
        }

        public static void InitLogger()
        {
            string name = string.Format("./client_log-{0:yyyy-MM-dd_hh-mm}.txt", DateTime.Now);
            if (File.Exists(name))
            {
                File.Delete(name);
            }
            fs = File.OpenWrite(name);
        }

        public static void SendString(string msg)
        {
            try
            {
                byte[] buffer;
                byte[] bufferType = new byte[2];
                bufferType[0] = 0x1;
                bufferType[1] = 0x1;
                byte[] bMsg = Encoding.UTF8.GetBytes(msg);
                int length = bufferType.Length + bMsg.Length;
                buffer = new byte[length];
                bufferType.CopyTo(buffer, 0);
                bMsg.CopyTo(buffer, bufferType.Length);
                RemotePhysics.client.GetStream().Write(buffer, 0, length);
                RemotePhysics.client.GetStream().Flush();
            }
            catch (System.InvalidOperationException ex)
            {
                throw ex;
            }
        }

        public static void SendByteMsg(byte[] bytes)
        {
            try
            {
                byte[] buffer;
                byte[] bufferType = new byte[2];
                bufferType[0] = 0x1;
                bufferType[1] = 0x2;
                int length = bufferType.Length + bytes.Length;
                buffer = new byte[length];
                bufferType.CopyTo(buffer, 0);
                bytes.CopyTo(buffer, bufferType.Length);
                RemotePhysics.client.GetStream().Write(buffer, 0, length);
                RemotePhysics.client.GetStream().Flush();
            }
            catch (System.InvalidOperationException ex)
            {
                throw ex;
            }
        }
    }
}
